# -*- coding: UTF-8 -*-
# 工具类
import numpy as np
from matplotlib import pyplot as plt


class Util:
    def __init__(self):
        self.buyerUtility = []

    def sthChanged(self, s):
        """判断是否有卖家改动了报价
        \ns: 卖家集合
        """
        for seller in s:
            if (seller.flag == True):
                return True
        return False

    def isRejected(self, sindex, t):
        """判断卖家的报价是否被买家拒绝
        \nsindex:卖家序号
        \nt:买家集合
        """
        if (sindex in t.w):
            return False
        else:
            return True

    def checkPoint(self, k, s, t, d):
        """显示当前状态，记录数据
        """
        s_profit = 0
        b_utility = 0
        print("\n=> k = %d" % (k))
        print("seller: w[], price, quality")
        for seller in s:
            print(seller.w, seller.price, seller.quality)
            s_profit += sum(seller.price)-seller.cost*len(t)
        print("buyer: w[], cost, utility:")
        for buyer in t:
            print(buyer.w, buyer.getCost(s), buyer.getUtility(s))
            b_utility += buyer.getUtility(s)
        d['x'].append(k)
        d['sellerProfit'].append(s_profit)
        d['buyerUtility'].append(b_utility)

    def checkPoint_SP(self, k, s, t, d):
        """显示当前状态，记录数据
        k:轮数
        s:卖家集合
        t:买家集合
        d:结果数据
        """
        s_profit = 0
        b_aoi = 0
        #print("\n=> k = %d" % (k))
        #print("seller: w[], price, l")
        for seller in s:
            #print(seller.w, seller.price, seller.l)
            s_profit += sum(seller.price)-seller.cost
        #print("buyer: w[], cost, AoI:")
        for buyer in t:
            #print(buyer.w, buyer.getCost(s), buyer.getAoI(s))
            b_aoi += buyer.getAoI(s)
        d['x'].append(k)
        d['sellerProfit'].append(s_profit)
        d['buyerAoI'].append(b_aoi)

    def initPlotData(self, mode='match'):
        """初始化绘图数据变量
        """
        d = {}
        if(mode == 'match'):
            d['x'] = []
            d['sellerProfit'] = []
            d['buyerUtility'] = []
        return d

    def initPlotData_SP(self, mode='match'):
        """初始化绘图数据变量
        """
        d = {}
        if(mode == 'match'):
            d['x'] = []
            d['sellerProfit'] = []
            d['buyerAoI'] = []
        return d

    def doPlot(self, pdata):
        """绘图
        """
        plt.plot(pdata['x'], pdata['sellerProfit'], label='seller')
        plt.plot(pdata['x'], pdata['buyerUtility'], label='buyer')
        plt.legend()
        plt.xlabel('round')
        plt.ylabel('profit/util')
        plt.title('fig 1.')
        plt.show()

    def doPlot_SP(self, pdata):
        """绘图
        """
        path = './fig/latest.png'
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(pdata['x'], pdata['sellerProfit'], label='seller')
        ax1.set_xlabel('round')
        ax1.set_ylabel('seller profit', color='steelblue')
        ax2 = ax1.twinx()
        ax2.plot(pdata['x'], pdata['buyerAoI'], label='buyer', color='r')
        ax2.set_ylabel('buyer AoI', color='r')
        plt.title('fig 1.')
        plt.savefig(path)
        plt.show()

    def plotDoubleData(self, x, data1, data2, namex, name1, name2):
        path = './fig/latest.png'
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        ax1.plot(x, data1)
        ax1.set_xlabel(namex)
        ax1.set_ylabel(name1, color='steelblue')
        ax1.set_ylim(bottom=0)
        ax2 = ax1.twinx()
        ax2.plot(x, data2, color='r')
        ax2.set_ylabel(name2, color='r')
        ax2.set_ylim(bottom=0)
        plt.title('fig 1.')
        plt.savefig(path)
        plt.show()
